/**
 * Created by Administrator on 2016/7/16.
 */
//在你的项目根目录下创建gulpfile.js，代码如下：

// 引入 gulp
var gulp = require('gulp');
var sass = require('gulp-ruby-sass');
var tinylr = require('tiny-lr');
var port = 35729;
// 引入组件
var htmlmin = require('gulp-htmlmin'), //html压缩
    imagemin = require('gulp-imagemin'),//图片压缩
    pngcrush = require('imagemin-pngcrush'),
    minifycss = require('gulp-minify-css'),//css压缩
    jshint = require('gulp-jshint'),//js检测
    uglify = require('gulp-uglify'),//js压缩
    concat = require('gulp-concat'),//文件合并
    rename = require('gulp-rename'),//文件更名
    notify = require('gulp-notify');//提示信息

// 压缩html
gulp.task('html', function() {
    return gulp.src('html/**/*.html')
        .pipe(htmlmin({collapseWhitespace: true}))
        .pipe(gulp.dest('./ready/html'))
        .pipe(notify({ message: 'html task ok' }));
});

// 压缩图片
gulp.task('img', function() {
    return gulp.src('img/**/*')
        .pipe(imagemin({
            progressive: true,
            svgoPlugins: [{removeViewBox: false}],
            use: [pngcrush()]
        }))
        .pipe(gulp.dest('./ready/img/'))
        .pipe(notify({ message: 'img task ok' }));
});

//编译sass文件
gulp.task('sass', function () {
    return sass('sass/*.scss')
        .on('error', function (err) {console.error('Error!', err.message);})
        .pipe(gulp.dest('./css'))
        .pipe(notify({ message: 'sass task ok' }));
});

// 合并、压缩、重命名css  引入sass是因为这样能在css任务执行前先完成sass的编译
gulp.task('css',['sass'], function() {
    return gulp.src('css/*.css')
        .pipe(concat('main.css'))
        .pipe(gulp.dest('./ready/css'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(minifycss())
        .pipe(gulp.dest('./ready/css'))
        .pipe(notify({ message: 'css task ok' }));
});

// 检查js
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'))
        .pipe(notify({ message: 'lint task ok' }));
});

// 合并、压缩js文件    引入lint是因为这样能在js任务执行前先完成lint的检测
gulp.task('js',['lint'], function() {
    return gulp.src('js/*.js')
        .pipe(concat('all.js'))
        .pipe(gulp.dest('./ready/js'))
        .pipe(rename({ suffix: '.min' }))
        .pipe(uglify())
        .pipe(gulp.dest('./ready/js'))
        .pipe(notify({ message: 'js task ok' }));
});



// 默认任务
gulp.task('default', function(){
    gulp.run( 'img' , 'css' , 'js' , 'html');
});

//启动本地服务器实时监听编译
tinylr().listen(port, function(){
    //实时监听编译sass css
    gulp.watch('sass/*.scss', function(){
        gulp.run('css');
    });
    //实时监听编译js
    gulp.watch('js/*.js', function(){
        gulp.run('js');
    });
    //实时监听编译html
    gulp.watch('html/**/*.html', function(){
        gulp.run('html');
    });
    //实时监听压缩img
    gulp.watch('img/**/*', function(){
        gulp.run('img');
    });
});